package mytweetdiary;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.http.RequestToken;
import twitter4j.http.AccessToken;

@SuppressWarnings("serial")
public class OauthCompletedServlet extends HttpServlet {
	private static final Logger log = Logger.getLogger(OauthCompletedServlet.class
			.getName());

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();

		if (user != null) {
			log.log(Level.INFO, "Request Token : "
					+ req.getParameter("oauth_token"));

			// get Access Token.
			TwitterManager tm = new TwitterManager(user);
			Twitter twitter = tm.getTwitterInstance();
			RequestToken requestToken = tm.getRequestToken();
			try {
				AccessToken accessToken = twitter
						.getOAuthAccessToken(requestToken);
				tm.saveAccessToken(accessToken);
			} catch (TwitterException te) {
				if (401 == te.getStatusCode()) {
					log.log(Level.INFO, "Unable to get the access token.");
				}
				else {
					te.printStackTrace();
				}
			}
			resp.sendRedirect("/index.jsp");
		} else {
			resp.sendRedirect(userService.createLoginURL(req.getRequestURI()));
		}
	}
}
